<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    width="40%" 
    @ok="handleSubmit" 
    showFooter
    destroyOnClose
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import {ref, computed, unref,useAttrs} from 'vue';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import { inputFormSchemas } from './data';
  import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import { saveOrUpdateArea , getArea, listAreaTreeSelect, type Area } from './api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<Area>({} as Area);

  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 90,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate;
   
      if (unref(isUpdate)) {
        record.value = await getArea({areaId: data.record.id}) || {} 
      }

      setFieldsValue({ 
        ...record.value,
        parentId: record.value.parentId === '0' ? undefined : record.value.parentId
      })

      updateSchema([
        {
          field: 'parentId',
          componentProps: {
            api: listAreaTreeSelect,
            isDisable: (node) => {
              return isUpdate.value && node.id === record.value.id
            },
            immediate: true,
            fieldNames: {
              pid: 'parentId',
              value: 'id',
              label: 'name',
            },
            params: {
              isBuildTree: false
            },
          },
        },
        {
          field: 'id',
          componentProps: {
            disabled: isUpdate.value,
          },
        },
      ]);

    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增区域' : '编辑区域'));

  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      await saveOrUpdateArea({...values}, unref(isUpdate));
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
